<!--
 * @Descripttion: 项目管理
 * @version: V1.0
 * @Author: GW
 * @Date: 2021-10-24 11:10:55
 * @LastEditors: GW
 * @LastEditTime: 2022-06-08 11:04:10
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="big-main-wrapper warehouse-type-wrapper project-manage-class" style="margin:2px 8px;">
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :span="2" v-if="permissions.includes('phaseGroup:add')">
                            <div class="btns" @click="editDataFun(1)">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="permissions.includes('phaseGroup:edit')">
                            <div class="btns" @click="editDataFun(2)">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="permissions.includes('phaseGroup:delete')">
                            <div class="btns" @click="remove">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                        <!-- <a-col :span="2">
                            <div class="btns">
                                <a-icon class="btns-icon" type="lock" />
                                <div class="btns-text">归档</div>
                            </div>
                        </a-col> -->
                    </a-col>
                </a-row>
            </div>
            <div class="table-wrapper-box">
                <a-tabs default-active-key="1" @change="callback">
                    <a-tab-pane key="1" tab="全部项目">

                    </a-tab-pane>
                    <a-tab-pane key="2" tab="我负责的项目">

                    </a-tab-pane>
                    <a-tab-pane key="3" tab="我参与的项目">

                    </a-tab-pane>
                </a-tabs>
                <a-table style="margin-top:0px !important" :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }" :columns="columns" :data-source="data" bordered>
                    <template slot="code" slot-scope="text,record">
                        <span class="a-label" @click="jumpDetails(record.id)">{{text}}</span>
                    </template>
                    <template slot="name" slot-scope="text,record">
                        <span class="a-label" @click="jumpDetails(record.id)">{{text}}</span>
                    </template>
                    <template slot="type" slot-scope="text">
                        {{typeName.get(text)}}
                    </template>
                    <template slot="status" slot-scope="text">
                        {{statusName.get(text + '')}}
                    </template>
                </a-table>
            </div>
        </div>

        <a-modal v-model="visible" :title="modalTitle" @cancel="()=>{visible = false}" class="phase-box" :width="800">
            <a-form-model :label-col="{span:8}" :wrapper-col="{span:14}">
                <a-row :span="24">
                    <a-col :span="12" v-for="item in frombackData" :key="item">
                        <a-form-model-item :label="item.name" :rules="[{ required: item.onFill,trigger:'input'}]">
                            <template v-if="item.columnType == '文本'">
                                <a-input :disable="item.onEdit" :placeholder="'请输入' + item.name" v-model.trim="item.value" />
                            </template>
                            <template v-if="item.columnType == '下拉选择'">
                                <a-select :disabled="!item.onEdit" v-model="item.value" @change="downSelectChange" style="width:220px;">
                                    <a-select-option v-for=" (select,index) in formatSelectJsonVal(item.dictCode,item.val)" :key="index" :value="select.key">
                                        {{select.label}}
                                    </a-select-option>
                                </a-select>
                            </template>
                            <template v-if="item.columnType == '下拉'">
                                <a-select :disabled="!item.onEdit" v-model="item.value" style="width:220px;">
                                    <a-select-option v-for=" (select,index) in formatRadioVal(item.val)" :key="index" :value="select.key">
                                        {{select.label}}
                                    </a-select-option>
                                </a-select>
                            </template>
                            <template v-if="item.columnType == '小数'">
                                <a-input :placeholder="'请输入' + item.name" onkeyup="value=value.toString().match(/^\d+(?:\.\d{0,5})?/)" v-model="item.value" />
                            </template>
                            <template v-if="item.columnType == '日期'">
                                <a-date-picker style="width:220px;" :placeholder="'请选择' + item.name" v-model="item.value" :disabled="!item.onEdit" @change="((date,dateString)=>{onChangeTime(date,dateString,item.code)})" />
                            </template>
                            <template v-if="item.columnType == '搜索多选'">
                                <a-input-search read-only :placeholder="'请输入' + item.name" v-model="liablePersonNames" @click="handleSearch" @search="handleSearch" />
                                <multi-select :ref="'headRef'" @clickItem="setValue"></multi-select>
                            </template>
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
            <template slot="footer">
                <a-button type="primary" @click="submitRequest">
                    确认
                </a-button>
                <a-button @click="()=>{visible = false}">
                    取消
                </a-button>
            </template>
        </a-modal>
    </div>
</template>
<script>

import { mapState } from "vuex";

import { list as listDesign } from "@/api/erp/voucherDesign"; //获取项目动态表单
import { list, remove, save, getCode } from "@/api/project/projectManage";

import multiSelect from "./components/multiSelect"
export default {
    components: {
        multiSelect
    },
    data () {
        return {
            frombackData: [],//动态字段
            sourceCode: 'Project',
            formId: null,
            data: [],
            columns: [],
            visible: false,
            pageSize: 20, // 每页多少条数据
            current: 1, // 当前页
            thisData: [], // 当前选中的数据
            visible: false, // 弹出框默认隐藏
            putStorage: [], // 入库
            outbound: [], // 出库
            selectedKeys: [],
            selectedRows: [],
            modalTitle: '',
            liablePersonNames: '',
            liablePersonIds: '',
            dict: JSON.parse(localStorage.getItem('dict')),//字典
            typeName: new Map(),//项目分类
            statusName: new Map(),//项目状态
        };
    },
    created () {
        this.getData();
        this.getFromDataSource();//获取动态字段
        this.getDictName();
    },
    activated () {
        this.getFromDataSource();//获取动态字段
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    methods: {
        getDictName () {
            //获取类型对应的字典名称
            let map = new Map();
            this.dict.forEach(item => {
                map.set(item.dictCode, item)
            });
            let back = map.get('project_type').dictDatas;
            back.forEach(item => {
                this.typeName.set(item.dictLabel, item.dictValue);
            });

            let status = map.get('project_status').dictDatas;
            status.forEach(item => {
                this.statusName.set(item.dictLabel, item.dictValue);
            });
            console.log(this.statusName);
        },
        getFromDataSource () {
            //动态表单结构
            listDesign({ source: this.sourceCode }).then(res => {
                if (res.code === 200) {
                    this.frombackData = res.data;
                    this.changeToTabMap();
                }
            })
        },
        changeToTabMap () {
            //数据处理（用于弹窗）
            const frombackDataAll = this.frombackData;
            this.columns = [];
            frombackDataAll.forEach(item => {
                let col = {
                    title: item.name,
                    dataIndex: item.code,
                    align: 'left',
                }
                if (item.code == 'code' || item.code == 'name' || item.code == 'type' || item.code == 'status') {
                    col.scopedSlots = { customRender: item.code };
                }
                if (item.onOff) {
                    this.columns.push(col);
                }
            });
            //过滤onOff 是否强制展示
            let frombackData = frombackDataAll.filter((item) => {
                return item.onOff == true && item.onEdit == true;
            });
            for (let i = 0; i < frombackData.length; i++) {
                let d = frombackData[i];

                this.$set(d, 'value', '');
                //------------------------------------------------------配置默认值
                // if (d.columnType == '下拉选择') {
                //     frombackData[i].val = this.formatSelectJsonVal(frombackData[i].dictCode);
                // }
            }
            this.frombackData = frombackData;
        },
        getCode () {
            //获取编码
        },
        onSelectChange (keys, rows) {
            this.selectedKeys = keys;
            this.selectedRows = rows;
        },
        editDataFun (type) {
            //新增 or 修改
            if (type == 1) {
                this.modalTitle = '新增项目';
                this.formId = null;
                this.liablePersonNames = '';
                this.liablePersonIds = '';
                this.frombackData.forEach(item => {
                    item.value = null;
                });
                this.visible = true;
            } else {
                if (this.selectedRows.length != 1) {
                    this.$message.warning('请选择一条数据修改');
                    return;
                }
                let editData = _.cloneDeep(this.selectedRows[0]);
                this.formId = editData.id;
                this.frombackData.forEach(item => {
                    for (const key in editData) {
                        if (item.code == key) {
                            if (item.columnType == '下拉选择') {
                                item.value = Number(editData[key]);
                            } else {
                                item.value = editData[key];
                            }
                        }
                    }
                });
                this.liablePersonNames = editData.liablePersonNames; //负责人
                this.liablePersonIds = editData.liablePersonIds;     //负责人id

                this.modalTitle = '修改项目';
                this.visible = true;
            }
        },
        getData () {
            // 获取收发类别数据
            const { pageSize, current } = this;
            let params = { size: pageSize, current: current };
            list(params).then(res => {
                if (res.code == 200) {
                    if (res.data.records.length > 0) {
                        this.data = res.data.records.map(r => {
                            return { ...r, key: r.id }
                        })

                        //处理自定义数据
                        this.data.forEach(element => {
                            if (element.defineFields != null || element.defineFields != '') {
                                let d = JSON.parse(element.defineFields);
                                for (const key in d) {
                                    element[key] = d[key];
                                }
                            }
                        });

                        console.log(this.data);
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        remove () {
            let that = this;
            this.$confirm({
                title: `是否确认删除 ${that.selectedRows[0].name}`,
                content: "",
                onOk () {
                    remove([that.selectedKeys.join(',')]).then(res => {
                        if (res.code == 200) {
                            that.selectedKeys = [];
                            that.selectedRows = [];
                            that.$message.success("删除成功");
                            that.getData();
                        } else {
                            that.$message.warning(res.message);
                        }
                    })
                },
                onCancel () { }
            });
        },
        submitRequest () {
            let requestData = {}
            this.frombackData.forEach(item => {
                requestData[item.code] = item.value;
            });
            requestData.liablePersonNames = this.liablePersonNames; //负责人
            requestData.liablePersonIds = this.liablePersonIds;     //负责人id
            if (requestData.name == null) {
                this.$message.warning('请输入项目名称');
                return;
            }
            requestData.id = this.formId;
            requestData.defineFields = '';
            //自定义字段处理

            let dataType2 = this.frombackData.filter(res => res.dataType == 2);//自定义的字段
            let abc = {};//要提交的自定义字段数据
            if (dataType2.length > 0) {
                dataType2.forEach(item => {
                    // this.$set(abc, item.code, item.value);
                    abc[item.code] = item.value;
                });
            }
            requestData.defineFields = JSON.stringify(abc);
            console.log(requestData);
            save(requestData).then(res => {
                if (res.code == 200) {
                    this.selectedKeys = [];
                    this.selectedRows = [];
                    this.$message.success("保存成功");
                    this.visible = false;
                    this.getData();
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        jumpDetails (id) {
            //跳转到详情页
            this.$router.push(`/project/projectDetails?id=${id}`)
        },
        onChangeTime (d, string, code) {
            //时间处理string
            // this.dateString = string;
            // this.code = code;
            let backData = {
                dateString: string,
                code: code
            }
            this.$emit('changetime', backData)
        },
        formatRadioVal (val) {
            let result = [];
            if (!val) return;
            let arr = val.split(',');
            arr.forEach(value => {
                result.push({
                    key: value,
                    label: value
                })
            })
            console.log("下拉数据转化：", result);
            return result;
            // return val && val != '' && val != null ? val.split(',') : '';
        },
        formatSelectJsonVal (code, val) {
            console.log('valvalvalvalval:', val)
            let thisVal = [];
            let backVal = [];
            if (code && code != null) {
                let dictData = JSON.parse(localStorage.getItem('dict'));
                dictData.forEach(item => {
                    if (item.dictCode == code) {
                        thisVal = item.dictDatas;
                    }
                });
                if (thisVal && thisVal != '' && thisVal != null) {
                    thisVal.forEach((item, index) => {
                        let obj = {
                            key: Number(item.dictLabel),
                            label: item.dictValue,
                        }
                        backVal.push(obj);
                    });
                }
            } else {
                if (val != null) {
                    thisVal = JSON.parse(val);
                    if (thisVal && thisVal != '' && thisVal != null) {
                        thisVal.forEach((item, index) => {
                            backVal.push(item);
                        });
                    }
                }
            }
            console.log(backVal)
            return backVal;
        },
        downSelectChange (value) {
            console.log(value);
            //发票
            // if (this.$route.path == '/procurement/purchaseInvoice') {
            //     if (value == 99) {
            //         this.changeInvoiceType = 0
            //     }else{
            //         this.changeInvoiceType = 1
            //     }

            //     this.$refs.dunamicSearchRef[0].checkSearch();
            // } else {
            // this.$emit('downSelectChange', value);
            // }
        },
        handleSearch () {
            console.log(this.$refs.headRef[0])
            this.$refs.headRef[0].showModal();
        },
        setValue (data) {
            console.log('valvalvalvalval:', data)
            let name = [];
            let id = [];
            data.forEach(item => {
                name.push(item.name);
                id.push(item.id);
            });
            this.liablePersonNames = name.join(',');
            this.liablePersonIds = id.join(',');

            console.log('负责人ids:', id, '负责人names:', name)
        },

    },
};
</script>
<style lang="less">
    // .content-box {
    //     height: 100%;
    //     width: 240px;
    //     display: flex;
    //     flex-flow: column;
    // }
    @import '~@/style/setting/inventory.less';
    .project-manage-class {
        .warehouse-type-wrapper {
            margin: 0px;
        }
        .phase-box {
            .ant-form-item {
                margin-bottom: 0px;
            }
        }
        .table-wrapper-box {
            height: calc(100% - 45px);
            overflow-y: auto;
        }
        .a-label {
            color: #1890ff;
            display: block;
            cursor: pointer;
        }
    }
</style>